package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.ThreadLocalUtil;
import com.zzyl.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    RoleResourceMapper roleResourceMapper;
    @javax.annotation.Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 根据用户id查询对应的资源数据
     *
     * @return
     */
    @Override
    public List<MenuVo> getMyMenus() {
        //Long userId = 1671403256519078138L;
        Long userId = ThreadLocalUtil.get();
        //查询数据
        List<MenuVo> menuVoList = resourceMapper.selectMenuByUserId(userId);
        //构建 parentNo -> List<MenuVo> 的映射
        Map<String, List<MenuVo>> parentMap = menuVoList.stream().collect(Collectors.groupingBy(MenuVo::getParentResourceNo));
        //递归构建我的菜单信息
        buildTree(menuVoList, parentMap);
        return parentMap.get(SuperConstant.ROOT_RESOURCE_PARENT_ID);
    }


    @Override
    public TreeVo resourceTreeVo(ResourceDto dto) {
      /*  String redisKey = "zzyl:resource:tree:vo";
        String redisdata = stringRedisTemplate.opsForValue().get(redisKey);
        if (StrUtil.isNotBlank(redisdata)){
            //如果redis缓存有数据则直接返回
            return JSON.parseObject(redisdata, TreeVo.class);
        }*/


        ResourceDto dtom = ResourceDto.builder().dataState(SuperConstant.DATA_STATE_0).resourceType(SuperConstant.MENU).build();
        List<Resource> resources = resourceMapper.selectList(dtom);
        Resource resourceNo = CollUtil.findOneByField(resources, "resourceNo", SuperConstant.ROOT_RESOURCE_PARENT_ID);
        TreeItemVo vo = resourcetreeitem(resourceNo, resources);
        return TreeVo.builder().items(List.of(vo)).build();


       /* TreeVo vo1 = TreeVo.builder().items(List.of(vo)).build();
        stringRedisTemplate.opsForValue().set(redisKey, JSON.toJSONString(vo1));
        return vo1;*/
    }

    @Override
    public List<ResourceVo> selectlist(ResourceDto dto) {
        List<Resource> resources = resourceMapper.selectList(dto);
        List<ResourceVo> vos = BeanUtil.copyToList(resources, ResourceVo.class);
        return vos;
    }

    @Override
    public void addresponse(ResourceDto dto) {
        Resource resource = BeanUtil.toBean(dto, Resource.class);
        Resource resource1 = resourceMapper.selectByResourceNo(dto.getParentResourceNo());
        String resourceNo = createResourceNo(resource, resource1);
        resource.setResourceNo(resourceNo);
        resourceMapper.insert(resource);
    }

    @Override
    public void enable(ResourceDto dto) {
        if (StrUtil.equals(dto.getDataState(), "0")) {
            String parentResourceNo = dto.getParentResourceNo();
            Resource parentResource = resourceMapper.selectByResourceNo(parentResourceNo);
            if (parentResource != null && parentResource.getDataState().equals("1")) {
                throw new BaseException(BasicEnum.PARENT_MENU_DISABLE);
            }
        }
        Resource resource = BeanUtil.toBean(dto, Resource.class);
        String resourceNo = dto.getResourceNo();
        resourceMapper.updateByResourceNo(resource.getResourceNo(), resource.getDataState());
        resourceMapper.updateByParentResourceNo(NoProcessing.processString(resourceNo), resource.getDataState());
    }

    @Override
    public void updateresource(ResourceDto dto) {
        Resource resource = BeanUtil.toBean(dto, Resource.class);
        resourceMapper.updateByPrimaryKeySelective(resource);
    }

    @Override
    public void deletesource(String menuId) {
        int i = resourceMapper.hasChildByMenuId(menuId);
        if (i > 0) throw new RuntimeException("存在子菜单，不允许删除");

        int i1 = roleResourceMapper.checkMenuExistRole(menuId);
        if (i1 > 0) throw new RuntimeException("菜单已分配，不允许删除");

        Resource resource = resourceMapper.selectByResourceNo(menuId);
        if (resource == null || resource.getDataState().equals(SuperConstant.DATA_STATE_0)) {
            throw new RuntimeException("菜单启用状态，不能删除");
        }
        resourceMapper.deleteByResourceNo(menuId);
    }

    /**
     * 创建资源的编号（已提供）
     * 创建资源的编号（已提供）
     * 创建资源的编号（已提供）
     */
    private String createResourceNo(Resource resource, Resource parentResource) {
        //判断是否是按钮，如果是按钮，则不限制层级
        if (!StrUtil.equals(resource.getResourceType(), SuperConstant.BUTTON)) {
            if (NoProcessing.processString(parentResource.getResourceNo()).length() / 3 >= 5) {
                //判断资源编号是否大于三级
                //100 001 000 000 000
                //100 001 001 000 000
                //100 001 001 001 000
                //100 001 001 001 001 001
                throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
            }
        }

        //根据父资源编号查询子资源
        ResourceDto dto = ResourceDto.builder().parentResourceNo(parentResource.getResourceNo()).build();
        List<Resource> resources = resourceMapper.selectList(dto);
        if (ObjectUtil.isEmpty(resources)) {
            //无下属节点，创建新的节点编号  100 001 001 001 000--->100 001 001 001 001
            return NoProcessing.createNo(parentResource.getResourceNo(), false);
        } else {
            //有下属节点，在已有的节点上追加，先获取已有节点的最大值--100001003000000
            Long maxNo = resources.stream().map(r -> Long.valueOf(r.getResourceNo())).max(Comparator.comparing(i -> i)).get();
            return NoProcessing.createNo(String.valueOf(maxNo), true);
        }
    }


    private TreeItemVo resourcetreeitem(Resource rootresourceNo, List<Resource> resourceslist) {
        TreeItemVo treeItemVo = TreeItemVo.builder().id(rootresourceNo.getResourceNo()).label(rootresourceNo.getResourceName()).build();
        Collection<Resource> resources = CollUtil.filterNew(resourceslist, resource -> StrUtil.equals(resource.getParentResourceNo(), rootresourceNo.getResourceNo()));
        List<TreeItemVo> collect = resources.stream().map(resource -> resourcetreeitem(resource, resourceslist)).collect(Collectors.toList());
        treeItemVo.setChildren(collect);
        return treeItemVo;
    }

    /**
     * 递归构建我的菜单信息（已提供）
     */
    private void buildTree(List<MenuVo> menuVoList, Map<String, List<MenuVo>> parentMap) {
        menuVoList.forEach(menuVo -> {
            //补全数据
            menuVo.setMeta(MenuMetaVo.builder().title(menuVo.getName()).build());
            menuVo.setRedirect("/" + menuVo.getName());
            //根据当前资源编号查询子资源
            List<MenuVo> childrenList = parentMap.get(menuVo.getResourceNo());
            if (CollUtil.isNotEmpty(childrenList)) {
                buildTree(childrenList, parentMap);
                menuVo.setChildren(childrenList);
            }
        });
    }
}
